#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import aiohttp
import asyncio
from typing import Optional, Dict, Any
from ..core.logger import Logger

class HttpClient:
    def __init__(self, cookie: Optional[str] = None):
        self.logger = Logger()
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Referer': 'https://www.bilibili.com',
        }
        if cookie:
            self.headers['Cookie'] = cookie
    
    async def get(self, url: str, params: Optional[Dict[str, Any]] = None) -> Dict:
        """发送GET请求"""
        async with aiohttp.ClientSession(headers=self.headers) as session:
            try:
                async with session.get(url, params=params) as response:
                    response.raise_for_status()
                    return await response.json()
            except Exception as e:
                self.logger.error(f"请求失败: {url}, 错误: {str(e)}")
                raise
    
    async def post(self, url: str, data: Optional[Dict[str, Any]] = None) -> Dict:
        """发送POST请求"""
        async with aiohttp.ClientSession(headers=self.headers) as session:
            try:
                async with session.post(url, json=data) as response:
                    response.raise_for_status()
                    return await response.json()
            except Exception as e:
                self.logger.error(f"请求失败: {url}, 错误: {str(e)}")
                raise
    
    async def download_file(self, url: str, save_path: str) -> None:
        """下载文件"""
        async with aiohttp.ClientSession(headers=self.headers) as session:
            try:
                async with session.get(url) as response:
                    response.raise_for_status()
                    with open(save_path, 'wb') as f:
                        while True:
                            chunk = await response.content.read(8192)
                            if not chunk:
                                break
                            f.write(chunk)
            except Exception as e:
                self.logger.error(f"下载失败: {url}, 错误: {str(e)}")
                raise 